#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define NUM_THREADS 32

pthread_t threads[NUM_THREADS];
pthread_t main_thread;
int threadid[NUM_THREADS];

#define MAX (10000000)
unsigned char isprime[NUM_THREADS][MAX+1];
unsigned int value[NUM_THREADS][MAX+1];


void *erastpt(void *threadptr)
{
        int i, j, thidx=*((int *)threadptr);
        unsigned int p=2, cnt=0;

        isprime[thidx][0]=0; value[thidx][0]=0;
        isprime[thidx][1]=0; value[thidx][1]=1;

        for(i=2; i<MAX+1; i++) { isprime[thidx][i]=1; value[thidx][i]=i; }

        while( (p*p) <=  MAX)
        {
            for(j=2*p; j<MAX+1; j+=p) isprime[thidx][j]=0;
            for(j=p+1; j<MAX+1; j++) { if(isprime[thidx][j]) { p=j; break; } }
        }

        for(i=0; i<MAX+1; i++) { if(isprime[thidx][i]) { cnt++; } }
        printf("\nThread=%d, Number of primes [0..%d]=%u", thidx, MAX, cnt);
}


void *testThread(void * tptr)
{
   int i, iterations;

   for(iterations=0;iterations<100;iterations++)
   {

       for(i=0;i<NUM_THREADS;i++)
       {
           threadid[i]=i;
           pthread_create(&threads[i], (void *)0, erastpt, (void *)&threadid[i]);
       }

       for(i=0;i<NUM_THREADS;i++)
           pthread_join(threads[i], NULL);
    
       }

   printf("\nThreaded test complete\n");

}


void main (void)
{
   int rc;

   rc = pthread_create(&main_thread, (void *)0, testThread, (void *)0);
   if (rc)
   {
       printf("ERROR; pthread_create() rc is %d\n", rc); perror(NULL); exit(-1);
   }

   pthread_join(main_thread, NULL);

   printf("TEST COMPLETE\n");

}
